<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/


jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAEmail extends JModel
{
    var $_data;
    var $_table;
    var $_pagination;
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function _buildQuery($limit = 0, $limitstart = 0){    		
    	global $mainframe, $option;
    	
    	$db =& JFactory::getDBO();
    	$option_1 = $option.'jaemail';
    	$search				= $mainframe->getUserStateFromRequest( $option_1.'.jaemail.search',              'search',           '',         'string' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option_1.'.jaemail.filter_order',		'filter_order',		'name',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option_1.'.jaemail.filter_order_Dir',	'filter_order_Dir',	'ASC',	'word' );
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );

		$search				= JString::strtolower( $search );
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir;
		
    	$where = ' WHERE 1=1 ';
    	
    	if($search){
    		$where = " AND LOWER(name) like ".$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )
    				. " or LOWER(subject) like ".$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
    	}
    	if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where .= ' AND published = 1';
			} else if ($filter_state == 'U' ) {
				$where .= ' AND published = 0';
			}
		}
        $query = "SELECT  * ".
				 "FROM 	`jos_ja_email` ".
				 $where.
				 $orderby;
      
        return $query;
    }
    
    /**
    * Get data list of email
    * @return array  Array of objects contain email data
    */
    function &getData(){
        // load data if it doesnnot already exists
        if(empty($this->_data)){
            $query = $this->_buildQuery();
            $this->_data = $this->_getList($query);
        }
        
        return $this->_data;
    }
    
    /**
    * Get email table instance
    * @return JTable Email table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance(JBPREFIX.'Email', 'JobBoardTable');
		}
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination()
	{
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Remove email record
	* @return Number of removed records
	*/
	function remove(){
	    $cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if($n){
	        $query = "DELETE FROM #__ja_email WHERE id = ". implode(" OR id = ", $cid);
	        $db = &JFactory::getDBO();
	        $db->setQuery($query);
	        if($db->query()){
	            return $n;
			}
		}
		
		return -1;
	}
	
	/**
	* Get email item by ID
	* @return Email Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table =& $this->_getTable();
		// Load the current item if it has been defined
		$edit	= JRequest::getVar('edit',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		$subscription_id	= intval(JRequest::getVar('subscription_id', 0));
		$template	= strval(JRequest::getVar('tpl', ''));
		
		if(!$cid[0] && $subscription_id && $template){
			$query = "SELECT  * ".
				 "\n FROM 	`jos_ja_email` ".
				 "\n WHERE subscription_id='$subscription_id' and name='$template'";
			$db = &JFactory::getDBO();				 
			$db->setQuery($query);		
			$item = $db->loadObject();	
			
			//JRequest::setVar('cid[]', $table->id);
			
		}
		elseif ($edit) {
			$table->load($cid[0]);				
		}		
		
	    if(!$item) $item = $table;
	  
	    return $item;	    
	}
	
	/**
	* Get email Item limit row
	* @return Email Table object
	*/
	
	function getItems(){
		global $mainframe, $option;
		
	    $limit				= $mainframe->getUserStateFromRequest( 'global.list.limit',							'limit',			$mainframe->getCfg( 'list_limit' ),	'int' );
		$limitstart			= $mainframe->getUserStateFromRequest( $option.'.jaemail.limitstart',		'limitstart',		0,				'int' );
		
		$db = &JFactory::getDBO();
		$db->setQuery($this->_buildQuery());
		
		$items = $db->loadObjectList();
		
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		// slice out elements based on limits
		$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
	}
			
	
	/** 
	* Store email item
	* @param array The post array
	*/
	function store(){
	    // Initialize variables
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post	= $this->getState( 'request' );
		
		if (!$row->bind( $post )) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_("Bind data false");
		}
		
		if ($row->check() != 'SUCCESS')
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return $row->check();
		}
      
		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_('Store fail');
			//return false;
		}
		
		$row->checkin();
		return $row->id;
	}
			
	function dopublish($publish){
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());		
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_email"
		. "\n SET published = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
	
	function getLanguages($client=0){
		$client	=& JApplicationHelper::getClientInfo($client);
		$path = JLanguage::getLanguagePath($client->path);
		$dirs = JFolder::folders( $path );
		$i = 0; $data['name'] = '';
		
		foreach ($dirs as $dir)
		{
			
				$files = JFolder::files( $path.DS.$dir, '^([-_A-Za-z]*)\.xml$' );
				foreach ($files as $file)
				{
					$data = JApplicationHelper::parseXMLLangMetaFile($path.DS.$dir.DS.$file);
					$row 			= new StdClass();
					$row->id 		= $i;
					$row->language 	= substr($file,0,-4);
			
					if (!is_array($data)) {
						continue;
					}
					foreach($data as $key => $value) {
						$row->$key = $value;
					}
					$rows[] = $row;
				}
				$i++;
			
		}	
		return $rows;
	}
	
	function parse_email_config(){
		global $option;
		include_once(JPATH_ADMINISTRATOR.DS.'components'.DS.$option.DS.'asset'.DS.'jaemail_config.php');		
	    
	    $rrrr = preg_split('/^==\s*(.+?)\s*==\s*$/ms', $EMAIL_TEMPLATES_CONFIG, -1, PREG_SPLIT_DELIM_CAPTURE);
	    $rrrr = array_map('trim', $rrrr);
	    if ($rrrr[0] == '') array_shift($rrrr);
	    for ($i=0;$i<count($rrrr);$i+=2){
	        $head = $rrrr[$i];
	        $body = $rrrr[$i+1];
	        $tags = array();
	        if (preg_match('/^TAGSET\s+(.+)\s*/', $head, $regs)){ // tagset found
	            foreach (preg_split('/[\r\n]+/', $body) as $l){
	                if ($l == '') continue;
	                list($k,$v) = explode(' - ', $l);
	                if (($k == '') || ($v == '')){
	                    fatal_error("Error in line: $l, no tag keyword or description present, check spaces around dash",0);
	                }
	                $tags[ trim($k) ] = trim($v);
	            }
	            $PARSED_EMAIL_TEMPLATES_CONFIG['tagset'][$regs[1]] = $tags;
	        } elseif (preg_match('/EMAIL TAGS\s+(.+)\s*/', $head, $regs)){ // email record found
	            $tagsets = array_map('trim', explode(',', $regs[1]));
	            $lines = preg_split('/[\r\n]+/', $body);
	            preg_match('/^(.+?) - (.+)/', $x=trim(array_shift($lines)), $regs);
	            $em = $regs[1];
	            list($em,$filename) = explode(':', $em, 2);
	            $comment = $regs[2];
	            foreach ($lines as $l){
	                if ($l == '') continue;
	                list($k,$v) = explode(' - ', $l);
	                if (($k == '') || ($v == '')){
	                    fatal_error("Error in line: $l, no tag keyword or description present, check spaces around dash",0);
	                }
	                $tags[ trim($k) ] = trim($v);
	            }
	            $PARSED_EMAIL_TEMPLATES_CONFIG['emails'][$em] = array(
	                'comment' => $comment,
	                'file' => $filename,
	                'tagsets' => $tagsets,
	                'tags' => $tags,
	            );
	        } else {
	            fatal_error('wrong EMAIL_TEMPLATES_CONFIG definition: ' . $head, 0);
	        }
	    }
	    return $PARSED_EMAIL_TEMPLATES_CONFIG;
	}
}
?>